﻿using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.ComponentModel;

namespace PMAF.K3Cloud.SCM.Bill.ServicePlugIn
{
    [HotUpdate]
    [Description("同步更新采购流水号当前数量")]
    public class SaleOrderSave : AbstractOperationServicePlugIn
    {
        /// <summary>
        /// 校验器
        /// </summary>
        /// <param name="e"></param>
        public override void OnAddValidators(AddValidatorsEventArgs e)
        {
            base.OnAddValidators(e);
            PurchaseSnValidator validator = new PurchaseSnValidator
            {
                AlwaysValidate = true,
                EntityKey = "FBillHead"
            };
            //e.Validators.Add(validator);
        }

        /// <summary>
        /// 操作开始前执行
        /// </summary>
        /// <param name="e"></param>
        public override void BeginOperationTransaction(BeginOperationTransactionArgs e)
        {
            foreach (DynamicObject entity in e.DataEntitys)
            {
                if (entity != null)
                {
                    DynamicObjectCollection entry = (DynamicObjectCollection)entity["SaleOrderEntry"];
                    string formId = entity["FFormId"].ToString();
                    int billId = Convert.ToInt32(entity["Id"]);
                    if(string.Equals(formId, "SAL_SaleOrder"))
                    {
                        //设置销售订单过滤条件并查询订单 SAL_SaleOrder
                        OQLFilter salOrderFilter = new OQLFilter
                        {
                            new OQLFilterHeadEntityItem() { FilterString = string.Format("FID='{0}'", billId) }
                        };
                        DynamicObject[] salOrders = BusinessDataServiceHelper.Load(Context, "SAL_SaleOrder", null, salOrderFilter);
                        //在原订单修改过程中保留行的信息
                        DynamicObjectCollection oldFlagEntries = new DynamicObjectCollection();
                        foreach (DynamicObject row in entry)
                        {
                            int currentEntryId = Convert.ToInt32(row["Id"]);
                            var qty = Convert.ToDecimal(row["Qty"]);
                            decimal oldQty = 0;
                            int oldPurchaseId = 0;
                            if (salOrders.Length > 0)
                            {
                                DynamicObjectCollection salOrderEntry = (DynamicObjectCollection)salOrders[0]["SaleOrderEntry"];
                                foreach (DynamicObject item in salOrderEntry)
                                {
                                    int oldEntryId = Convert.ToInt32(item["Id"]);
                                    //如果有保留行，放入保留行的集合
                                    if(currentEntryId == oldEntryId)
                                    {
                                        oldQty = Convert.ToDecimal(item["Qty"]);
                                        oldPurchaseId = Convert.ToInt32(item["F_PMAF_PurchaseSN_Id"]);
                                        oldFlagEntries.Add(item);
                                    }
                                }
                            }
                            var purchaseId = Convert.ToInt32(row["F_PMAF_PurchaseSN_Id"]);
                            //设置采购流水号过滤条件并查询流水号
                            OQLFilter purchaseSnFilter = new OQLFilter
                            {
                                new OQLFilterHeadEntityItem() { FilterString = string.Format("FID='{0}'", purchaseId) }
                            };
                            OQLFilter oldPurchaseSnFilter = new OQLFilter
                            {
                                new OQLFilterHeadEntityItem() { FilterString = string.Format("FID='{0}'", oldPurchaseId) }
                            };
                            DynamicObject[] purchaseSns = BusinessDataServiceHelper.Load(Context, "PMAF_PurchaseSn", null, purchaseSnFilter);
                            DynamicObject[] oldPurchaseSns = BusinessDataServiceHelper.Load(Context, "PMAF_PurchaseSn", null, oldPurchaseSnFilter);
                            if (purchaseSns.Length > 0 && oldPurchaseSns.Length > 0)  //修改前后都有流水号
                            {
                                //新旧流水号相同
                                if(Convert.ToInt32(purchaseSns[0]["Id"]) == Convert.ToInt32(oldPurchaseSns[0]["Id"]))
                                {
                                    //更新流水号的当前数量
                                    purchaseSns[0]["F_PMAF_CurrentQty"] = Convert.ToDecimal(purchaseSns[0]["F_PMAF_CurrentQty"]) - qty + oldQty;
                                    BusinessDataServiceHelper.Save(Context, purchaseSns);
                                }
                                else   //新旧流水号不同
                                {
                                    //更新流水号的当前数量
                                    purchaseSns[0]["F_PMAF_CurrentQty"] = Convert.ToDecimal(purchaseSns[0]["F_PMAF_CurrentQty"]) - qty;
                                    oldPurchaseSns[0]["F_PMAF_CurrentQty"] = Convert.ToDecimal(oldPurchaseSns[0]["F_PMAF_CurrentQty"]) + oldQty;
                                    BusinessDataServiceHelper.Save(Context, purchaseSns);
                                    BusinessDataServiceHelper.Save(Context, oldPurchaseSns);
                                }
                            }
                            else if(purchaseSns.Length > 0 && oldPurchaseSns.Length == 0)
                            {
                                //更新流水号的当前数量
                                purchaseSns[0]["F_PMAF_CurrentQty"] = Convert.ToDecimal(purchaseSns[0]["F_PMAF_CurrentQty"]) - qty;
                                BusinessDataServiceHelper.Save(Context, purchaseSns);
                            }
                            else if(purchaseSns.Length == 0 && oldPurchaseSns.Length > 0)
                            {
                                //更新流水号的当前数量
                                oldPurchaseSns[0]["F_PMAF_CurrentQty"] = Convert.ToDecimal(oldPurchaseSns[0]["F_PMAF_CurrentQty"]) + qty;
                                BusinessDataServiceHelper.Save(Context, oldPurchaseSns);
                            }
                        }
                        //对于原单修改中被删除行的处理
                        if(salOrders.Length > 0)
                        {
                            DynamicObjectCollection salOrderEntry = (DynamicObjectCollection)salOrders[0]["SaleOrderEntry"];
                            foreach(var item in salOrderEntry)
                            {
                                int oldEntryId = Convert.ToInt32(item["Id"]);
                                //判断是否是被删除行
                                int i = 0;
                                if(oldFlagEntries.Count > 0)
                                {
                                    foreach(var row in oldFlagEntries)
                                    {
                                        int flagId = Convert.ToInt32(row["Id"]);
                                        if (oldEntryId != flagId)
                                        {
                                            i++;
                                        }
                                    }
                                }
                                //对被删除行的数据，流水号当前数量要加上被删除行的数量
                                if (oldFlagEntries.Count == i)
                                {
                                    var purchaseId = item["F_PMAF_PurchaseSN_Id"];
                                    decimal oldQty = Convert.ToDecimal(item["Qty"]);
                                    //设置采购流水号过滤条件并查询流水号
                                    OQLFilter purchaseSnFilter = new OQLFilter
                                    {
                                        new OQLFilterHeadEntityItem() { FilterString = string.Format("FID='{0}'", purchaseId) }
                                    };
                                    DynamicObject[] purchaseSns = BusinessDataServiceHelper.Load(Context, "PMAF_PurchaseSn", null, purchaseSnFilter);
                                    if (purchaseSns.Length > 0)
                                    {
                                        //更新流水号的当前数量
                                        purchaseSns[0]["F_PMAF_CurrentQty"] = Convert.ToDecimal(purchaseSns[0]["F_PMAF_CurrentQty"]) + oldQty;
                                        BusinessDataServiceHelper.Save(Context, purchaseSns);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
